<template>
    <div>
        <p>
            <button class="btn btn-bold btn-success btn-round " v-on:click="add()">
                <i class="ace-icon fa fa-edit bigger-110"></i>
                新增
            </button>&nbsp;
            <button class="btn btn-bold btn-success btn-round " v-on:click="list(1)">
                <i class="ace-icon fa fa-refresh bigger-110"></i>
                刷新
            </button>
        </p>

        <pagination ref="pagination" v-bind:list="list" v-bind:itemCount="8"></pagination>

        <table id="simple-table" class="table  table-bordered table-hover">
            <thead>
            <tr>
                <th>编号ID</th>
                <th>信息名称</th>
                <th>信息标签</th>
                <th class="hidden-480">操作</th>
            </tr>
            </thead>

            <tbody>
            <tr v-for="roles in roless" :key="roles.index">
                <td>{{roles.id}}</td>
                <td>{{roles.name}}</td>
                <td>{{roles.description}}</td>

                <td>
                    <div class="hidden-sm hidden-xs btn-group">
                        <button class="btn btn-xs btn-primary" v-on:click="editRolesUser(roles)">
                            <i class="ace-icon fa fa-user bigger-120"></i>用户附权
                        </button>
                        <button class="btn btn-xs btn-success" v-on:click="editRoleResources(roles)">
                            <i class="ace-icon fa fa-user-plus bigger-120"></i>添加权限
                        </button>
                        <button class="btn btn-xs btn-info" v-on:click="edit(roles)">
                            <i class="ace-icon fa fa-pencil bigger-120"></i>编辑信息
                        </button>
                        <button class="btn btn-xs btn-danger" v-on:click="del(roles.id)">
                            <i class="ace-icon fa fa-trash-o bigger-120"></i>删除
                        </button>
                    </div>

                    <div class="hidden-md hidden-lg">
                        <div class="inner pos-rel">
                            <button class="btn btn-minier btn-primary dropdown-toggle"
                                    data-toggle="dropdown" data-position="auto">
                                1
                                <i class="ace-icon fa fa-cog icon-only bigger-120"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close">
                                <li>
                                    <a href="#" class="tooltip-info" data-rel="tooltip" title="view"
                                       v-on:click="edit(roles)">
                                        <span class="blue">
                                            <i class="ace-icon fa fa-pencil bigger-120"></i>
                                        </span>
                                    </a>
                                </li>
                                <li>
                                    <a href="#" class="tooltip-info" data-rel="tooltip" title="view"
                                       v-on:click="del(roles.id)">
                                        <span class="blue">
                                            <i class="ace-icon fa fa-trash bigger-120"></i>
                                        </span>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>

        <div id="form-modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">角色表表单</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-2 control-label">角色名</label>
                                <div class="col-sm-10">
                                    <input
                                            v-model="roles.name"
                                            type="text" class="form-control"
                                            placeholder="角色名">
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="col-sm-2 control-label">角色描述</label>
                                <div class="col-sm-10">
                                    <input
                                            v-model="roles.description"
                                            type="text" class="form-control"
                                            placeholder="角色描述">
                                </div>
                            </div>

                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" v-on:click="save()">保存</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
        <!--增加role_resources编辑框-->
        <div id="roles_user_modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title">角色用户管理配置</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <!--所有users-->
                            <div class="col-md-6">
                                <table id="user-table" class="table table-hover">
                                    <tbody>
                                    <tr v-for="user in users" :key="user.index">
                                        <td>{{user.loginName }}</td>
                                        <td class="text-right">
                                            <a v-on:click="addRolesUser(user)" href="javascript:;" class="">
                                                <i class="ace-icon fa fa-arrow-circle-right blue bigger-180"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                            <!--角色-用户关联的users-->
                            <div class="col-md-6">
                                <table id="roles-user-table" class="table table-hover">
                                    <tbody>
                                    <tr v-for="user in rolesUsers" :key="user.index">
                                        <td>{{user.loginName }}</td>
                                        <td class="text-right">
                                            <a v-on:click="deleteRolesUser(user)" href="javascript:;" class="">
                                                <i class="ace-icon fa fa-trash orange bigger-180"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-bold btn-success btn-round " data-dismiss="modal">
                            <i class="ace-icon fa fa-times bigger-110"></i>
                            关闭
                        </button>&nbsp;
                        <button class="btn btn-bold btn-success btn-round " v-on:click="saveRolesUser()">
                            <i class="ace-icon fa fa-save bigger-110"></i>
                            保存
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div id="role_resources_modal" class="modal fade" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title">角色权限管理配置</h4>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <ul id="roleTree" class="ztree"></ul>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button class="btn btn-bold btn-success btn-round " data-dismiss="modal">
                            <i class="ace-icon fa fa-times bigger-110"></i>
                            关闭
                        </button>&nbsp;
                        <button class="btn btn-bold btn-success btn-round " v-on:click="saveRoleResources()">
                            <i class="ace-icon fa fa-save bigger-110"></i>
                            保存
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import Pagination from "../../components/pagination";

    export default {
        name: "system-single-info",
        components: {Pagination},
        data: function () {
            return {
                roles: {},
                roless: [],
                users: [],
                rolesUsers: [],
                zTree: {},
                resourcess: [],
            }
        },
        mounted: function () {
            let _this = this;
            _this.$refs.pagination.size = 10;
            _this.list(1);

        },
        methods: {
            /**
             * 列表查询
             */
            list(page) {
                let _this = this;
                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roles/list',
                    {
                        currentPage: page,
                        initPageNum: _this.$refs.pagination.size
                    }).then((responseDTO) => {
                    Loading.hide();
                    console.log("查询角色表列表：", responseDTO);
                    let resp = responseDTO.data;
                    _this.roless = resp.responseData.list;
                    _this.$refs.pagination.render(page, resp.responseData.sumPage);
                })
            },
            /**
             * 点击【新增】
             */
            add() {
                let _this = this;
                console.log("为不引起eslint提醒，调用_list:" + _this);
                _this.roles = {};
                $("#form-modal").modal("show");
            },
            /**
             * 点击【保存】
             */
            save(page) {
                let _this = this;

                //保存校验，1!=1去掉自动生成的代码第一个||或
                if (1 != 1
                    || !Validator.require(_this.roles.name, "角色名")
                    || !Validator.length(_this.roles.name, "角色名", 3, 50)
                    || !Validator.require(_this.roles.description, "角色描述")
                    || !Validator.length(_this.roles.description, "角色描述", 3, 100)
                ) {
                    return;
                }

                Loading.show();
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roles/save', _this.roles)
                    .then((responseAdd) => {
                        Loading.hide();
                        console.log("保存角色表结果：", responseAdd);
                        let resp = responseAdd.data;
                        if (resp.success) {
                            $("#form-modal").modal('hide');
                            _this.list(1);
                            //添加提示
                            Toast.success("保存成功！");
                        } else {
                            Toast.warning(resp.responseMsg);
                        }
                    })
            },
            /**
             * 点击【编辑】
             */
            edit(roles) {
                let _this = this;

                _this.roles = $.extend({}, roles);
                /*$("#form-modal").modal("show");*/
                SessionStorage.set(SESSION_KEY_COURSE,roles);
                _this.$router.push("/business/content");
            },
            /**
             * 点击【删除】
             */
            del(id) {
                let _this = this;
                Confirm.show("删除角色表后不可恢复!", function () {
                    Loading.show();
                    _this.$ajax.delete(process.env.VUE_APP_SERVER + '/system/admin/roles/delete/' + id)
                        .then((responseDel) => {
                            Loading.hide();
                            console.log("删除角色表内容：", responseDel);
                            let resp = responseDel.data;
                            if (resp.success) {
                                _this.list(1);
                                Toast.success("删除成功！");
                            }
                        });
                });
            },
            /**
             * 编辑角色
             */
            editRoleResources(roles) {
                let _this = this;
                _this.roles = $.extend({}, roles);
                _this.loadResources();
                $("#role_resources_modal").modal("show");
            },
            /**
             * 加载树
             */
            loadResources() {
                let _this = this;
                Loading.show();
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/resources/load-resources-tree')
                    .then((responseTree) => {
                        Loading.hide();
                        let response = responseTree.data;
                        _this.resourcess = response.responseData;
                        //初始化树
                        _this.initResourcesTree();
                        //角色资源查询方法
                        _this.getRoleResources();
                    });
            },
            /**
             * 初始化树
             */
            initResourcesTree() {
                let _this = this;
                let setting = {
                    check: {
                        enable: true,
                    },
                    data: {
                        simpleData: {
                            idKey: "id",
                            pIdKey: "parent",
                            rootPId: "",
                            enable: true
                        }
                    }
                };
                _this.zTree = $.fn.zTree.init($("#roleTree"), setting, _this.resourcess);
                //全部展开
                _this.zTree.expandAll(true);
            },
            /**
             * 保存权限方法
             */
            saveRoleResources() {
                let _this = this;
                //1.获取zTree节点数据
                let resources = _this.zTree.getCheckedNodes();
                console.log("勾选的资源：", resources)
                //2.保存时，只需要保存资源id，使用id数字进行资源传递
                let resourcesIds = [];
                for (let i = 0; i < resources.length; i++) {
                    resourcesIds.push(resources[i].id);
                }

                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roles/save-resources-roles',
                    {
                        id: _this.roles.id,
                        resourcesIds: resourcesIds
                    }).then((responseResources) => {
                    let response = responseResources.data;
                    if (response.success) {
                        Toast.success("保存角色成功");
                    } else {
                        Toast.warning(response.responseMsg);
                    }
                });
            },
            /**
             * 查询角色-资源关联数据
             */
            getRoleResources() {
                let _this = this;
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/roles/get-resources-roles/' + _this.roles.id)
                    .then((responseRoRe) => {
                        let response = responseRoRe.data;
                        let resources = response.responseData;
                        //勾选查询到的资源，先把树的所有资源清空勾选，再勾选查询到的节点
                        _this.zTree.checkAllNodes(false);
                        for (let i = 0; i < resources.length; i++) {
                            let node = _this.zTree.getNodeByParam("id", resources[i]);
                            _this.zTree.checkNode(node, true);
                        }
                    });
            },
            /**
             * 点击弹出user选项框
             */
            editRolesUser(roles){
                let _this=this;
                _this.roles=$.extend({},roles);
                _this.listUsers();
                $("#roles_user_modal").modal("show");
            },
            /**
             * 查询所有user
             */
            listUsers(){
                let _this=this;
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/user/list',{
                    page:1,
                    size:999
                }).then((responseUser)=>{
                    let response=responseUser.data;
                    if(response.success){
                        _this.users=response.responseData.list;
                        console.log(_this.users);
                        //查找角色用户
                        _this.listRolesUsers();
                    }else{
                        Toast.warning(response.responseMsg);
                    }
                });
            },
            /**
             * 添加角色用户
             */
            addRolesUser(user){
                let _this=this;
                //如果当前要添加的用户已经在右侧列表，则不再添加
                let users=_this.rolesUsers;
                for(let i=0;i<users.length;i++){
                    if(user===users[i]){
                        //如果不=则跳出循环
                        return;
                    }
                }
                //将点击的对象user，增加到rolesUsers
                _this.rolesUsers.push(user);
            },
            /**
             * 删除角色用户
             * 依赖vue的双向数据绑定特性，可以将复杂的页面操作变为简单的数据操作
             * angular、微信小程序也有双向数据绑定
             */
            deleteRolesUser(user){
                let _this=this;
                Tool.removeObj(_this.rolesUsers,user);
            },
            /**
             * 保存角色用户
             */
            saveRolesUser(){
                let _this=this;
                let users=_this.rolesUsers;
                //保存user_id，使用id数组进行参数传递
                let userIds=[];
                for(let i=0;i<users.length;i++){
                    userIds.push(users[i].id);
                }
                _this.$ajax.post(process.env.VUE_APP_SERVER + '/system/admin/roles/save-roles-users',
                    {
                        id:_this.roles.id,
                        usersIds:userIds
                    }).then((responseRolesUsers)=>{
                        console.log("保存角色用户结果：",responseRolesUsers);
                        let response=responseRolesUsers.data;
                        if(response.success){
                            Toast.success("角色添加到用户成功");
                            $("#roles_user_modal").modal("hide");
                        }else{
                            Toast.warning(response.responseMsg);
                        }
                });
            },
            /**
             * 加载角色用户关联数据
             */
            listRolesUsers(){
                let _this=this;
                _this.rolesUsers=[];
                //查关联表，结果都是userId，需要显示loginName，这里通过通过自定义mapper（user表和roles_user表关联数据）
                _this.$ajax.get(process.env.VUE_APP_SERVER + '/system/admin/roles/list-roles-users/'+_this.roles.id)
                .then((responseUserLoginName)=>{
                    let response=responseUserLoginName.data;
                    let userIds=response.responseData;
                    //根据加载到的用户id，到用户数组users中查找用户对象，列表显示
                    for(let i=0;i<userIds.length;i++){
                        for(let j=0;j<_this.users.length;j++){
                            if(userIds[i]===_this.users[j].id){
                                _this.rolesUsers.push(_this.users[j]);
                            }
                        }
                    }
                });
            },
        }
    }
</script>

<style scoped>

</style>